package uvsq.acsis.projects.xml.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

@SuppressWarnings("restriction")
public abstract class Marshaller {
	
	/*
	 * Convert a JAXB document object in a String representing the XML document
	 */
	public static String writeJAXBString( Object document)throws JAXBException, IOException {
		
		StringWriter str= new StringWriter();
		
		Class<?> clazz = document.getClass();
	    
	    JAXBContext context =JAXBContext.newInstance( clazz.getPackage().getName() );
	    javax.xml.bind.Marshaller m = context.createMarshaller();
	    m.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
	    m.marshal(document,str );
	    
	    return str.getBuffer().toString();
	}
	
	/*
	 * Convert a String into a JAXB document object 
	 */
	@SuppressWarnings({ "unchecked" })
	public static <T> T writeJAXBObject(T obj,String xmlString) throws JAXBException,IOException{
		
		StringReader str= new StringReader(xmlString);
		
		JAXBContext jc = JAXBContext.newInstance(obj.getClass().getPackage().getName());

		Unmarshaller u = jc.createUnmarshaller();

		Object result=null;
		try {
			result = u.unmarshal(str);
		} catch (JAXBException e) {
			throw new JAXBException("Erreur survenue lors du traitement JAXB->Object",e);
		}
		
		return (T) result;
	}

}
